#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <string>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Base64.cpp"
#include "RSA1.cpp"
#define PORT 3490
#define BACKLOG 10
#define MAXDATASIZE 1000
using namespace std;
int main(int argc,char **argv)
{
	int sockfd,numbytes;
	char buf[MAXDATASIZE];
	struct hostent *he;
	struct sockaddr_in their_addr;
	if(argc !=2){
		fprintf(stderr, "usage:client hostname\n");
		exit(1);
	}
	if((he=gethostbyname(argv[1]))==NULL){
		herror("get host by name");
		exit(1);
	}
	if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){
		perror("socket error");
		exit(1);
	}
	their_addr.sin_family=AF_INET;
	their_addr.sin_port=htons(PORT);
	their_addr.sin_addr=*((struct in_addr *)he->h_addr);
	bzero(&(their_addr.sin_zero),sizeof(their_addr.sin_zero));
	if(connect(sockfd,(struct sockaddr *)&their_addr,sizeof(struct sockaddr))==-1){
		perror("connect error");
		exit(1);
	}
	string message="hello zyl";
	string output="";
	ofstream fout("key.txt");
	int n,e,d;
	RSA_Initialize(n,e,d);
	fout<<d<<" "<<n;
	fout.close();
	char * enc_output=Base64Encode(message.c_str(), message.length(), true);
	string str=enc_output;
	RSA_Encrypt(e,n,str,output);
	if(!fork()){
		if(send(sockfd,output.c_str(),output.size(),0)==-1)
			perror("send error");
		close(sockfd);
		exit(0);
	}
	close(sockfd);
	return 0;
}